package com.ssyc.common.quanzi;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.lzy.ninegrid.ImageInfo;
import com.lzy.ninegrid.NineGridView;
import com.lzy.ninegrid.preview.NineGridViewClickAdapter;
import com.ssyc.common.R;
import com.ssyc.common.base.BaseApplication;
import com.ssyc.common.base.Constants;
import com.ssyc.common.base.NineImageLoader;
import com.ssyc.common.base.SpKeys;
import com.ssyc.common.bean.BusInfo;
import com.ssyc.common.bean.ResultInfo;
import com.ssyc.common.glide.ImageUtil;
import com.ssyc.common.http.HttpAdress;
import com.ssyc.common.http.HttpUtils;
import com.ssyc.common.manager.AccountUtils;
import com.ssyc.common.manager.BqaManager;
import com.ssyc.common.utils.AlertDialogUtil;
import com.ssyc.common.utils.DateUtils;
import com.ssyc.common.utils.GsonUtil;
import com.ssyc.common.utils.SPUtil;
import com.ssyc.common.utils.UiUtils;
import com.ssyc.common.view.dialog.CustomDialogManager;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * 圈子适配器
 * Created by Administrator on 2018/6/25 0025.
 */

public class QuanZiRvAdapter extends BaseQuickAdapter<QuanZiInfo.CirclelistBean, BaseViewHolder> {

    private Activity activtiy;

    private RecyclerView recyclerView;

    private Context context;

    private ArrayList<ImageInfo> imageInfo;

    //适配器
    private CircleDetailsRvAdapter adapter;

    //弹框相关的PopUpWindow
    private PopupWindow popupWindow;

    private TextView tvZan, tvPl, tvZf;

    List<QuanZiInfo.CirclelistBean> data = new ArrayList<>();

    public QuanZiRvAdapter(RecyclerView recyclerView, Activity activtiy, Context context, int layoutResId, @Nullable List<QuanZiInfo.CirclelistBean> data) {
        super(layoutResId, data);
        this.activtiy = activtiy;
        this.context = context;
        this.recyclerView = recyclerView;
        this.data = data;
    }

    @Override
    protected void convert(final BaseViewHolder holder, final QuanZiInfo.CirclelistBean item) {
        //头像
        ImageView lvHead = holder.getView(R.id.lv_head);
        lvHead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (AccountUtils.getAccount(context).equals(item.getUser_id()) ||
                        TextUtils.isEmpty(item.getUser_id())) {
                    SPUtil.put(context, SpKeys.CIRCLETYPE, 1);
                } else {
                    SPUtil.put(context, SpKeys.CIRCLETYPE, 2);
                }

                Intent intent = new Intent(context, PersonInfoActivity.class);
                intent.putExtra("data", item);
                context.startActivity(intent);
            }
        });
        //姓名
        TextView tvName = holder.getView(R.id.tv_name);
        //内容
        TextView tvContent = holder.getView(R.id.tv_content);
        //时间
        TextView tvTime = holder.getView(R.id.tv_time);
        //评论的图标
        final ImageView lvComment = holder.getView(R.id.lv_comment);

        //删除按钮
        TextView tvDelete = holder.getView(R.id.tv_delete);
        if ("".equals(item.getUser_pic()) && "".equals(item.getUser_name())
                || item.getUser_id().equals(AccountUtils.getAccount(context))) {
            //自己条目显示删除键
            tvDelete.setVisibility(View.VISIBLE);
        } else {
            tvDelete.setVisibility(View.GONE);
        }

        //设置头像
        if ("".equals(item.getUser_pic()) && "".equals(item.getUser_name())) {
            //自己条目
            ImageUtil.displayImage(context, lvHead, AccountUtils.getName(context));
            //设置自己姓名
            tvName.setText(AccountUtils.getName(context));
        } else {
            //其他条目
            ImageUtil.displayImage(context, lvHead, item.getUser_pic());
            //设置姓名
            tvName.setText(item.getUser_name());
        }

        //设置内容
        tvContent.setText(item.getContent());

        //设置时间
        tvTime.setText(DateUtils.fromToday(item.getUpdate_time()));

        //点赞整体条目
        final RelativeLayout rl_likelist_group = holder.getView(R.id.rl_likelist_group);

        //已点赞的名单
        final TextView tv_likelist = holder.getView(R.id.tv_likelist);

        tvDelete.setOnClickListener(new View.OnClickListener() {
            //删除圈子消息
            @Override
            public void onClick(View v) {
                //删除自己的评论
                AlertDialogUtil.showAlertDialog(context, "确定删除吗?", new AlertDialogUtil.onClickListener() {
                    @Override
                    public void onClickOk() {
                        doDeletQuanzi(item.getRow_id(), holder.getLayoutPosition() - 1);
                    }
                });
            }
        });

        //点赞、评论、转发
        lvComment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //点击评论弹出评论的PopUpWindow
                view = View.inflate(context, R.layout.common_pop_comment, null);
                tvZan = view.findViewById(R.id.tv_zan);
                tvPl = view.findViewById(R.id.tv_pinglun);
                tvZf = view.findViewById(R.id.tv_zhuanfa);

                //获取所有点赞的名称
                String likeNames = tv_likelist.getText().toString().trim();
                if (likeNames.contains(SPUtil.getString(context, SpKeys.NAME))) {
                    //自己已经点错赞
                    tvZan.setText("取消");
                } else {
                    tvZan.setText(" 赞   ");
                }

                //点赞的点击事件
                tvZan.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //点赞
                        if ("赞".equals(tvZan.getText().toString().trim())) {
                            doDzAction(item, rl_likelist_group, tv_likelist);
                        } else if ("取消".equals(tvZan.getText().toString().trim())) {
                            doCancelDzAction(item, rl_likelist_group, tv_likelist);
                        }

                        if (popupWindow != null && popupWindow.isShowing()) {
                            popupWindow.dismiss();
                        }
                    }

                });

                //评论的点击事件
                tvPl.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (popupWindow != null && popupWindow.isShowing()) {
                            popupWindow.dismiss();
                        }

                        //通过EventBus发送消息给Activity界面通知显示底部的评论布局和软键盘
                        EventBus.getDefault().post(new BusInfo("showcontent", holder.getLayoutPosition(), item.getRow_id() + ""));

                    }
                });
                //转发的点击事件
                tvZf.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        popupWindow.dismiss();
                        //转发
                        doZfAction(item);

                    }
                });

                popupWindow = new PopupWindow(view, WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);
                popupWindow.setTouchable(true);
                popupWindow.setFocusable(true);
                popupWindow.setBackgroundDrawable(new BitmapDrawable());

                view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
                int mShowMorePopupWindowWidth = view.getMeasuredWidth();
                int mShowMorePopupWindowHeight = view.getMeasuredHeight();

                if (popupWindow.isShowing()) {
                    popupWindow.dismiss();
                } else {
                    int heightlvComment = lvComment.getHeight();

                    popupWindow.showAsDropDown(lvComment, -mShowMorePopupWindowWidth - 20,
                            -(mShowMorePopupWindowHeight + heightlvComment) / 2);
                }
            }

        });

        if (item.getLikelist() != null && item.getLikelist().size() != 0) {

            //有点赞显示
            rl_likelist_group.setVisibility(View.VISIBLE);
            String like = "";

            for (int i = 0; i < item.getLikelist().size(); i++) {
                if (TextUtils.isEmpty(item.getLikelist().get(i).getUser_name())) {
                    //自己的名字不显示需获取本地保存的姓名
                    like = like + AccountUtils.getName(context);
                } else {
                    like = like + item.getLikelist().get(i).getUser_name();
                }
                if (i != item.getLikelist().size() - 1) {
                    like = like + ",";
                }
            }
            tv_likelist.setText(like);

        } else {
            //无点赞内容不显示
            rl_likelist_group.setVisibility(View.GONE);
        }

        //设置九宫格图片数据
        initNineData(item);

        //九宫格展示图片
        NineGridView ngv = holder.getView(R.id.ninegv);
        ngv.setImageLoader(new NineImageLoader());
        ngv.setAdapter(new NineGridViewClickAdapter(context, imageInfo));

        //评论数据
        final List<QuanZiInfo.CirclelistBean.CommentlistBean> comments = item.getCommentlist();

        //展示评论内容的RV
        final RecyclerView rv = holder.getView(R.id.lv_content);
        adapter = new CircleDetailsRvAdapter(context, R.layout.base_item_rv_list_comment,
                comments);
        BqaManager.setRv(null, context,
                adapter, rv, null);

        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, final int position) {
                //条目点击事件
                if (item.getCommentlist().get(position).getUser_name().equals(SPUtil.getString(context, SpKeys.NAME))) {


                    //删除自己的评论
                    AlertDialogUtil.showAlertDialog(context, "确定删除吗?", new AlertDialogUtil.onClickListener() {
                        @Override
                        public void onClickOk() {
                            doDeletCommentAction(comments, item, position);
                        }
                    });

                } else {
                    //回复别人
                    String json = GsonUtil.objectToJson(item);
                    //通过EventBus发送消息给Activity界面通知显示底部的评论布局和软键盘
                    EventBus.getDefault().post(new BusInfo("huifucomment",
                            position, json));
                }
            }
        });
    }

    /**
     * 删除圈子消息
     */
    private void doDeletQuanzi(int row_id, final int pos) {

        Map<String, String> map = new HashMap<>();
        map.put("type", "13");
        map.put("acc", AccountUtils.getAccount(context));
        map.put("role", AccountUtils.getRole(context));
        map.put("circlerowid", row_id + "");
        map.put("platform", "8");

        HttpUtils.post(HttpAdress.ZFCIRCLE, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                CustomDialogManager.dissmiss();
                UiUtils.Toast(BaseApplication.ERROR + ",删除失败", false);
            }

            @Override
            public void onResponse(String response, int id) {
                CustomDialogManager.dissmiss();
                if (!TextUtils.isEmpty(response)) {
                    ResultInfo info = null;
                    try {
                        info = GsonUtil.jsonToBean(response, ResultInfo.class);
                    } catch (Exception e) {
                        Log.i("test", Constants.PARSEDATAERROR);
                    }
                    if (null != info) {
                        if ("200".equals(info.getState())) {
                            //返回成功
                            UiUtils.Toast("删除成功", false);
                            //第一步:通知朋友圈界面进行刷新操作
//                            BusInfo busInfo = new BusInfo();
//                            busInfo.setType(MyQuanziActivity.UPDATE);
//                            EventBus.getDefault().post(busInfo);
                            data.remove(pos);
                            notifyDataSetChanged();

                        } else {
                            UiUtils.Toast("删除失败" + Constants.ERRORSTATE + info.getState(), false);
                            Log.i("test", Constants.ERRORSTATE + info.getState());
                        }
                    } else {
                        Log.i("test", Constants.EMPTY);
                    }
                } else {
                    Log.i("test", Constants.EMPTY);
                }
            }
        });
    }

    /**
     * 转发
     */
    private void doZfAction(QuanZiInfo.CirclelistBean info) {
        CustomDialogManager.show(context, "转发中...");
        Map<String, String> map = new HashMap<>();
        map.put("type", "14");
        map.put("acc", AccountUtils.getAccount(context));
        map.put("role", AccountUtils.getRole(context));
        map.put("circlerowid", info.getRow_id() + "");
        map.put("platform", "8");
        map.put("acc2", info.getUser_id() + "");
        map.put("role2", info.getRole() + "");
        map.put("usernickname2", info.getUser_name());
        HttpUtils.post(HttpAdress.ZFCIRCLE, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                CustomDialogManager.dissmiss();
                UiUtils.Toast(BaseApplication.ERROR + ",转发失败", false);
            }

            @Override
            public void onResponse(String response, int id) {
                CustomDialogManager.dissmiss();
                if (!TextUtils.isEmpty(response)) {
                    ResultInfo info = null;
                    try {
                        info = GsonUtil.jsonToBean(response, ResultInfo.class);
                    } catch (Exception e) {
                        Log.i("test", Constants.PARSEDATAERROR);
                    }
                    if (null != info) {
                        if ("200".equals(info.getState())) {
                            //返回成功
                            UiUtils.Toast("转发成功", false);
                            //第一步:通知朋友圈界面进行刷新操作
                            BusInfo busInfo = new BusInfo();
                            busInfo.setType(MyQuanziActivity.UPDATE);
                            EventBus.getDefault().post(busInfo);
                        } else {
                            UiUtils.Toast("转发失败" + Constants.ERRORSTATE + info.getState(), false);
                            Log.i("test", Constants.ERRORSTATE + info.getState());
                        }
                    } else {
                        Log.i("test", Constants.EMPTY);
                    }
                } else {
                    Log.i("test", Constants.EMPTY);
                }
            }
        });
    }


    /**
     * 设置九宫格图片数据的方法
     */
    private void initNineData(QuanZiInfo.CirclelistBean data) {
        imageInfo = new ArrayList<>();

        if (!TextUtils.isEmpty(data.getUser_picture1())) {
            ImageInfo info = new ImageInfo();
            info.setThumbnailUrl(data.getS_user_picture1());
            info.setBigImageUrl(data.getUser_picture1());
            imageInfo.add(info);
        }
        if (!TextUtils.isEmpty(data.getUser_picture2())) {
            ImageInfo info = new ImageInfo();
            info.setThumbnailUrl(data.getS_user_picture2());
            info.setBigImageUrl(data.getUser_picture2());
            imageInfo.add(info);
        }
        if (!TextUtils.isEmpty(data.getUser_picture3())) {
            ImageInfo info = new ImageInfo();
            info.setThumbnailUrl(data.getS_user_picture3());
            info.setBigImageUrl(data.getUser_picture3());
            imageInfo.add(info);
        }
        if (!TextUtils.isEmpty(data.getUser_picture4())) {
            ImageInfo info = new ImageInfo();
            info.setThumbnailUrl(data.getS_user_picture4());
            info.setBigImageUrl(data.getUser_picture4());
            imageInfo.add(info);
        }
        if (!TextUtils.isEmpty(data.getUser_picture5())) {
            ImageInfo info = new ImageInfo();
            info.setThumbnailUrl(data.getS_user_picture5());
            info.setBigImageUrl(data.getUser_picture5());
            imageInfo.add(info);
        }
        if (!TextUtils.isEmpty(data.getUser_picture6())) {
            ImageInfo info = new ImageInfo();
            info.setThumbnailUrl(data.getS_user_picture6());
            info.setBigImageUrl(data.getUser_picture6());
            imageInfo.add(info);
        }
        if (!TextUtils.isEmpty(data.getUser_picture7())) {
            ImageInfo info = new ImageInfo();
            info.setThumbnailUrl(data.getS_user_picture7());
            info.setBigImageUrl(data.getUser_picture7());
            imageInfo.add(info);
        }
        if (!TextUtils.isEmpty(data.getUser_picture8())) {
            ImageInfo info = new ImageInfo();
            info.setThumbnailUrl(data.getS_user_picture8());
            info.setBigImageUrl(data.getUser_picture8());
            imageInfo.add(info);
        }
        if (!TextUtils.isEmpty(data.getUser_picture9())) {
            ImageInfo info = new ImageInfo();
            info.setThumbnailUrl(data.getS_user_picture9());
            info.setBigImageUrl(data.getUser_picture9());
            imageInfo.add(info);
        }
    }


    /**
     * 删除评论的操作
     *
     * @param position
     */
    private void doDeletCommentAction(final List<QuanZiInfo.CirclelistBean.CommentlistBean> comments, QuanZiInfo.CirclelistBean item, final int position) {
        CustomDialogManager.show(context, "删除中...");
        Map<String, String> map = new HashMap<>();
        map.put("type", "8");
        map.put("acc", AccountUtils.getAccount(context));
        map.put("role", AccountUtils.getRole(context));
        map.put("circlerowid", getData().get(position).getRow_id() + "");
        map.put("platform", "8");
        map.put("comment_id", item.getCommentlist().get(position).getComment_id() + "");
        HttpUtils.post(HttpAdress.ZFCIRCLE, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                CustomDialogManager.dissmiss();
                UiUtils.Toast(BaseApplication.ERROR + ",删除失败", false);
            }

            @Override
            public void onResponse(String response, int id) {
                CustomDialogManager.dissmiss();
                if (!TextUtils.isEmpty(response)) {
                    ResultInfo info = null;
                    try {
                        info = GsonUtil.jsonToBean(response, ResultInfo.class);
                    } catch (Exception e) {
                        Log.i("test", Constants.PARSEDATAERROR);
                    }

                    if (null != info) {
                        if ("200".equals(info.getState())) {
                            //返回成功
                            UiUtils.Toast("删除成功", false);
                            //第一步:通知朋友圈界面进行刷新操作
                            BusInfo busInfo = new BusInfo();
                            busInfo.setType(MyQuanziActivity.UPDATE);
                            EventBus.getDefault().post(busInfo);

                            //更新适配器
                            comments.remove(position);
                            adapter.notifyDataSetChanged();
                        } else {
                            UiUtils.Toast("删除失败" + Constants.ERRORSTATE + info.getState(), false);
                            Log.i("test", Constants.ERRORSTATE + info.getState());
                        }
                    } else {
                        Log.i("test", Constants.EMPTY);
                    }
                } else {
                    Log.i("test", Constants.EMPTY);
                }
            }
        });
    }


    /**
     * 提交点赞的数据
     */
    private void doDzAction(QuanZiInfo.CirclelistBean item, final RelativeLayout rl_likelist_group,
                            final TextView tv_likelist) {

        Map<String, String> map = new HashMap<>();
        map.put("type", "3");
//        map.put("acc", "17607196654");
//        map.put("role", "2");
        map.put("acc", AccountUtils.getAccount(context));
        map.put("role", AccountUtils.getRole(context));
        map.put("circlerowid", item.getRow_id() + "");
        map.put("platform", "8");

        HttpUtils.post(HttpAdress.QUANZI, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {

                UiUtils.Toast("网络无响应，请检查网络连接", false);

            }

            @Override
            public void onResponse(String response, int id) {

                if (!TextUtils.isEmpty(response)) {
                    QuanZiInfo info = null;
                    try {
                        info = GsonUtil.jsonToBean(response, QuanZiInfo.class);
                    } catch (Exception e) {
                        Log.i("test", Constants.PARSEDATAERROR);
                    }

                    if (null != info) {
                        if ("200".equals(info.getState())) {
                            //返回成功
                            UiUtils.Toast("点赞成功", false);
                            //第一:更新当前头布局的点赞内容
                            UpdateHeadViewByZan(rl_likelist_group, tv_likelist);
                        } else {
                            UiUtils.Toast(Constants.ERRORSTATE + info.getState(), false);
                            Log.i("test", Constants.ERRORSTATE + info.getState());
                        }
                    } else {
                        Log.i("test", Constants.EMPTY);
                    }
                } else {
                    Log.i("test", Constants.EMPTY);
                }
            }
        });
    }

    /**
     * 取消点赞
     */
    private void doCancelDzAction(QuanZiInfo.CirclelistBean item, final RelativeLayout rl_likelist_group, final TextView tv_likelist) {

        CustomDialogManager.show(context, "点赞中...");
        Map<String, String> map = new HashMap<>();
        map.put("type", "4");
        map.put("acc", AccountUtils.getAccount(context));
        map.put("role", AccountUtils.getRole(context));
        map.put("circlerowid", item.getRow_id() + "");
        map.put("platform", "8");

        HttpUtils.post(HttpAdress.CLICKZAN, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                CustomDialogManager.dissmiss();
                UiUtils.Toast(BaseApplication.ERROR + ",取消赞失败", false);
            }

            @Override
            public void onResponse(String response, int id) {
                CustomDialogManager.dissmiss();
                if (!TextUtils.isEmpty(response)) {
                    ResultInfo info = null;
                    try {
                        info = GsonUtil.jsonToBean(response, ResultInfo.class);
                    } catch (Exception e) {
                        Log.i("test", Constants.PARSEDATAERROR);
                    }

                    if (null != info) {
                        if ("200".equals(info.getState())) {

                            //返回成功
                            UiUtils.Toast("取消赞成功", false);

                            //第一:更新当前头布局的点赞内容
                            UpdateHeadViewByCancelZan(rl_likelist_group, tv_likelist);

                        } else {
                            UiUtils.Toast("取消赞失败" + Constants.ERRORSTATE + info.getState(), false);
                            Log.i("test", Constants.ERRORSTATE + info.getState());
                        }
                    } else {
                        Log.i("test", Constants.EMPTY);
                    }
                } else {
                    Log.i("test", Constants.EMPTY);
                }
            }
        });
    }

    /**
     * 点赞成功后更新头布局的数据
     */
    private void UpdateHeadViewByZan(RelativeLayout rl_likelist_group, TextView tv_likelist) {
        if (rl_likelist_group.getVisibility() == View.GONE) {
            rl_likelist_group.setVisibility(View.VISIBLE);
            tv_likelist.setText(SPUtil.getString(context, SpKeys.NAME));
        } else {
            String content = tv_likelist.getText().toString().trim();
            tv_likelist.setText(content + "," + SPUtil.getString(context, SpKeys.NAME));
        }
    }

    /**
     * 取消赞成功后更新头布局的数据
     */
    private void UpdateHeadViewByCancelZan(RelativeLayout rl_likelist_group, TextView tv_likelist) {
        String likeNames = tv_likelist.getText().toString().trim();
        String ownName = SPUtil.getString(context, SpKeys.NAME);
        String deletNames = "";
        if (!likeNames.startsWith(ownName) && likeNames.endsWith(ownName)) {
            //以要删除的字符串开头
            deletNames = "," + ownName;
        } else if (likeNames.startsWith(ownName) && !likeNames.endsWith(ownName)) {
            deletNames = ownName;
        } else if (likeNames.startsWith(ownName) && likeNames.endsWith(ownName)) {
            deletNames = ownName;
        } else {
            deletNames = "," + ownName;
        }
        //做删除字符串的操作
        String resString = likeNames.replaceAll(deletNames, "");
        if (TextUtils.isEmpty(resString)) {
            //删除后没有点赞人数时
            tv_likelist.setText("");
            rl_likelist_group.setVisibility(View.GONE);
        } else {
            rl_likelist_group.setVisibility(View.VISIBLE);
            tv_likelist.setText(resString);
        }
    }
}













